# 人脸识别模块：负责加载学生人脸库、检测人脸、匹配识别、语音播报
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import face_recognition
import os
import pyttsx3
from config.settings import (
    STUDENT_PHOTO_DIR, FACE_MATCH_TOLERANCE,
    SPEAK_RATE, SPEAK_VOLUME
)

# 初始化语音播报引擎
engine = pyttsx3.init()
engine.setProperty('rate', SPEAK_RATE)
engine.setProperty('volume', SPEAK_VOLUME)

# 全局变量：存储学生人脸特征和姓名
student_face_encodings = []
student_names = []
def put_chinese_text(image, text, position, font_path="simhei.ttf", font_size=32, color=(0, 255, 0)):
    pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(pil_image)
    font = ImageFont.truetype(font_path, font_size)
    draw.text(position, text, font=font, fill=(color[2], color[1], color[0]))  # PIL颜色是RGB，OpenCV是BGR
    return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)

def load_student_face_database():
    """加载本地学生人脸库（从student_photos文件夹）"""
    global student_face_encodings, student_names
    # 清空原有数据（避免重复加载）
    student_face_encodings.clear()
    student_names.clear()

    # 遍历照片文件夹
    for filename in os.listdir(STUDENT_PHOTO_DIR):
        if filename.endswith(('.jpg', '.jpeg', '.png')):
            # 提取姓名和照片路径
            name = os.path.splitext(filename)[0]
            photo_path = os.path.join(STUDENT_PHOTO_DIR, filename)
            # 加载照片并提取人脸特征
            image = face_recognition.load_image_file(photo_path)
            face_encoding = face_recognition.face_encodings(image)[0]  # 每人1张照片
            # 添加到列表
            student_face_encodings.append(face_encoding)
            student_names.append(name)
    
    print(f"✅ 人脸库加载完成：共{len(student_names)}名学生")
    return student_names

def recognize_face(frame, hand_detected):
    """
    实时人脸识别（需手势+人脸同时出现才触发）
    :param frame: 视频帧（BGR格式）
    :param hand_detected: 是否检测到手势（来自gesture_detection模块）
    :return: frame（绘制人脸框+姓名的画面）、recognized_name（识别到的姓名，无则返回None）
    """
    recognized_name = None
    # 检测画面中的人脸
    face_locations = face_recognition.face_locations(frame)
    face_encodings = face_recognition.face_encodings(frame, face_locations)
    face_detected = len(face_locations) > 0

    # 手势+人脸同时出现，才进行匹配
    if hand_detected and face_detected:
        for face_encoding, face_location in zip(face_encodings, face_locations):
            # 与学生人脸库匹配
            matches = face_recognition.compare_faces(
                student_face_encodings, face_encoding, tolerance=FACE_MATCH_TOLERANCE
            )
            name = "未知学生"
            if True in matches:
                first_match_index = matches.index(True)
                name = student_names[first_match_index]
                recognized_name = name
                # 语音播报（只播报一次，避免重复）
                engine.say(f"这位同学是{name}")
                engine.runAndWait()
                print(f"📌 识别成功：{name}")
            
            # 在画面上绘制人脸框和姓名
            top, right, bottom, left = face_location
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
            frame = put_chinese_text(
                frame, name, (left, top-10), 
                font_size=24, color=(0, 255, 0)
            )
    
    return frame, recognized_name

def release_face_resource():
    """释放人脸识别资源（程序退出时调用）"""
    engine.stop()